import { ObjectLiteral, SelectQueryBuilder } from "typeorm";
import { FieldConfig } from "src/config";
import { PaginationData } from "./model";

type PaginationOption = {
    limit?: number;
    page?: number;
};

export async function pagination<T extends ObjectLiteral>(queryBuilder: SelectQueryBuilder<T>, option: PaginationOption = {}) {
    option.limit ||= FieldConfig.QUERY_LIMIT;
    option.page ||= 1;

    const skip = (option.page - 1) * option.limit;
    const [list, count] = await queryBuilder
        .take(option.limit)
        .skip((option.page - 1) * option.limit)
        .getManyAndCount();

    const data = new PaginationData<T>();
    data.list = list;
    data.count = count;
    data.limit = option.limit;
    data.nextPage = list.length + skip >= count ? 0 : option.page + 1;
    data.hasNext = data.nextPage > 0;
    return data;
}
